package org.idontknow.firstsinglechar;

import java.lang.Exception;

/**
 * an algorithm to find the first single character in a string, ex:
 *        "abccdeff" should return 'b'
 * without performance consideration, complexity: O(n^2)
 * those algorithm geeks are crazy, what's the point of creating an non-general
 * purpose algorithm with meaningless high performance(plus illegible codes)? damned fools...
 *
 * @author: ZHAO Xinyu, 17 Oct, 2006, at FT R&D
 */

class FirstSingleChar {

  public static void main(String[] args) {

    FirstSingleChar obj = new FirstSingleChar();
    try{
      System.out.println(args[0]);
      System.out.println(obj.find(args[0]));
    }catch(Exception e) {
      System.out.println("There is no this sort of char!!");
    }
//    System.out.println(obj.rearSubArray("this is a test string".toCharArray(), 20));
//    System.out.println(obj.isIn('x', "this is a test string".toCharArray()));  
  }
  
  public char find(String in) throws Exception{

    char[] converted = in.toCharArray();
    char[] counted = new char[converted.length];

    if(converted.length == 1)
      return converted[0];
    else 
      for(int i=0; i < converted.length-1; i++)  {
        if(!isIn(converted[i], counted)) {
          if(!isIn(converted[i], rearSubArray(converted, i+1)))
            return converted[i];
          counted[i] = converted[i];
          //        System.out.println(counted);
        }
      }
    if(!isIn(converted[converted.length-1], counted))
        return converted[converted.length-1];
    else  
        throw new Exception();
  }

  public boolean isIn(char toFind, char[] array) {

    for(int i=0; i < array.length; i++)
      if(toFind == array[i])
        return true;
    return false;
  }

  public char[] rearSubArray(char[] source, int index) {

    if(index > source.length)
      System.err.println("index out of bound error!!");

    char[] result = new char[source.length-index];

    for(int i=index; i < source.length; i++)
      result[i-index] = source[i];

    return result;
  }
}
